const CouponImportService = require('../services/CouponImportService');
const CouponExportService = require('../services/CouponExportService');
const logger = require('../utils/logger');
const multer = require('multer');
const path = require('path');

// 配置multer用于文件上传
const storage = multer.memoryStorage();
const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    // 只允许Excel文件
    console.log('上传文件信息:', {
      originalname: file.originalname,
      mimetype: file.mimetype,
      size: file.size
    });
    
    const allowedTypes = [
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-excel',
      'application/octet-stream' // 某些系统可能将Excel文件识别为此类型
    ];
    
    // 检查文件扩展名
    const fileExt = path.extname(file.originalname).toLowerCase();
    const allowedExtensions = ['.xlsx', '.xls'];
    
    if (allowedTypes.includes(file.mimetype) && allowedExtensions.includes(fileExt)) {
      cb(null, true);
    } else {
      console.log('文件类型不匹配:', file.mimetype, '扩展名:', fileExt, '允许的类型:', allowedTypes);
      cb(new Error('只支持Excel文件格式(.xlsx, .xls)'), false);
    }
  },
  limits: {
    fileSize: 10 * 1024 * 1024 // 10MB限制
  }
});

class CouponImportController {
  constructor() {
    this.importService = new CouponImportService();
    this.exportService = new CouponExportService();
  }

  /**
   * 下载优惠券Excel模板
   * GET /admin/template/coupon.xlsx
   */
  async downloadTemplate(req, res) {
    try {
      console.log('开始生成优惠券Excel模板');
      
      const buffer = this.exportService.generateTemplate();
      
      // 设置响应头
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', 'attachment; filename="coupon_template.xlsx"');
      res.setHeader('Content-Length', buffer.length);
      
      // 发送文件
      res.send(buffer);
      
      console.log('优惠券Excel模板下载成功');
    } catch (error) {
      console.error('下载模板失败:', error);
      res.status(500).json({
        success: false,
        message: '模板生成失败',
        error: error.message
      });
    }
  }

  /**
   * 导出优惠券数据
   * GET /admin/export/coupon
   */
  async exportCoupons(req, res) {
    try {
      const filters = {
        status: req.query.status,
        discount_type: req.query.discount_type,
        validity_type: req.query.validity_type,
        created_from: req.query.created_from,
        created_to: req.query.created_to,
        valid_from: req.query.valid_from,
        valid_to: req.query.valid_to,
        title: req.query.title,
        orderBy: req.query.orderBy,
        orderDirection: req.query.orderDirection,
        limit: req.query.limit,
        offset: req.query.offset
      };
      
      // 移除空值
      Object.keys(filters).forEach(key => {
        if (filters[key] === undefined || filters[key] === '') {
          delete filters[key];
        }
      });
      
      console.log('开始导出优惠券数据', { filters });
      
      const buffer = await this.exportService.exportCoupons(filters);
      
      // 生成文件名
      const timestamp = new Date().toISOString().split('T')[0].replace(/-/g, '');
      const filename = `coupons_export_${timestamp}.xlsx`;
      
      // 设置响应头
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
      res.setHeader('Content-Length', buffer.length);
      
      // 发送文件
      res.send(buffer);
      
      console.log('优惠券数据导出成功', { filename });
    } catch (error) {
      console.error('导出优惠券数据失败:', error);
      res.status(500).json({
        success: false,
        message: '数据导出失败',
        error: error.message
      });
    }
  }

  /**
   * 导出优惠券统计报告
   * GET /admin/export/coupon/statistics
   */
  async exportStatistics(req, res) {
    try {
      console.log('开始生成优惠券统计报告');
      
      const buffer = await this.exportService.exportCouponStatistics();
      
      // 生成文件名
      const timestamp = new Date().toISOString().split('T')[0].replace(/-/g, '');
      const filename = `coupon_statistics_${timestamp}.xlsx`;
      
      // 设置响应头
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
      res.setHeader('Content-Length', buffer.length);
      
      // 发送文件
      res.send(buffer);
      
      console.log('优惠券统计报告导出成功', { filename });
    } catch (error) {
      console.error('导出统计报告失败:', error);
      res.status(500).json({
        success: false,
        message: '统计报告生成失败',
        error: error.message
      });
    }
  }

  /**
   * 优惠券导入校验
   * POST /admin/import/coupon
   */
  async importCoupons(req, res) {
    const uploadMiddleware = upload.single('file');
    
    uploadMiddleware(req, res, async (err) => {
      if (err) {
        console.error('文件上传失败:', err);
        return res.status(400).json({
          success: false,
          message: '文件上传失败',
          error: err.message
        });
      }
      
      try {
        if (!req.file) {
          return res.status(400).json({
            success: false,
            message: '请选择要上传的Excel文件'
          });
        }
        
        console.log('开始处理优惠券导入文件', { 
          filename: req.file.originalname,
          size: req.file.size 
        });
        
        const startTime = Date.now();
        
        // 解析Excel文件
        const rawData = await this.importService.parseExcelFile(req.file.buffer);
        
        // 校验和规范化数据
        const validationResults = await this.importService.validateAndNormalizeData(rawData);
        
        const processingTime = Date.now() - startTime;
        
        const response = {
          success: true,
          message: '文件校验完成',
          statistics: {
            total_rows: validationResults.totalRows,
            valid_rows: validationResults.validRows,
            error_rows: validationResults.errorRows,
            warning_rows: validationResults.warningRows
          },
          processing_time_ms: processingTime,
          has_errors: validationResults.errors.length > 0,
          has_warnings: validationResults.warnings && validationResults.warnings.length > 0,
          errors: validationResults.errors,
          warnings: validationResults.warnings || [],
          valid_data: validationResults.validData
        };
        
        console.log('优惠券导入校验完成', {
          total_rows: validationResults.totalRows,
          valid_rows: validationResults.validRows,
          error_rows: validationResults.errorRows,
          processing_time_ms: processingTime
        });
        
        res.json(response);
        
      } catch (error) {
        console.error('导入校验失败:', error);
        res.status(500).json({
          success: false,
          message: '导入校验失败',
          error: error.message
        });
      }
    });
  }

  /**
   * 执行优惠券导入
   * POST /admin/import/coupon/execute
   */
  async executeImport(req, res) {
    try {
      const { validData } = req.body;
      
      if (!validData || !Array.isArray(validData)) {
        return res.status(400).json({
          success: false,
          message: '缺少有效的导入数据'
        });
      }
      
      console.log('开始执行优惠券导入', { count: validData.length });
      
      const startTime = Date.now();
      
      // 执行导入
      const results = await this.importService.importCoupons(validData, req.user?.id || 1);
      
      const processingTime = Date.now() - startTime;
      
      console.log('优惠券导入完成', {
        created: results.created,
        updated: results.updated,
        errors: results.errors.length,
        processing_time_ms: processingTime
      });
      
      res.json({
        success: true,
        message: '优惠券导入完成',
        results: {
          created: results.created,
          updated: results.updated,
          errors: results.errors.length,
          processing_time_ms: processingTime
        },
        errors: results.errors
      });
      
    } catch (error) {
      console.error('执行导入失败:', error);
      res.status(500).json({
        success: false,
        message: '执行导入失败',
        error: error.message
      });
    }
  }

  /**
   * 生成错误报告CSV
   * POST /admin/import/coupon/errors
   */
  async generateErrorReport(req, res) {
    try {
      const { errors } = req.body;
      
      if (!errors || !Array.isArray(errors)) {
        return res.status(400).json({
          success: false,
          message: '缺少错误数据'
        });
      }
      
      console.log('生成错误报告', { errorCount: errors.length });
      
      const errorsBuffer = this.generateErrorsCSV(errors);
      
      // 生成文件名
      const timestamp = new Date().toISOString().split('T')[0].replace(/-/g, '');
      const filename = `coupon_import_errors_${timestamp}.csv`;
      
      res.setHeader('Content-Type', 'text/csv; charset=utf-8');
      res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
      res.setHeader('Content-Length', errorsBuffer.length);
      
      res.send(errorsBuffer);
      
      console.log('错误报告生成成功', { filename });
      
    } catch (error) {
      console.error('生成错误报告失败:', error);
      res.status(500).json({
        success: false,
        message: '生成错误报告失败',
        error: error.message
      });
    }
  }





  /**
   * 生成错误报告CSV
   */
  generateErrorsCSV(errors) {
    const csvHeader = 'Row,Title,Errors\n';
    const csvRows = errors.map(error => {
      const title = (error.title || '').replace(/"/g, '""');
      const errorMessages = error.errors.join('; ').replace(/"/g, '""');
      return `${error.row},"${title}","${errorMessages}"`;
    }).join('\n');
    
    const csvContent = csvHeader + csvRows;
    return Buffer.from('\uFEFF' + csvContent, 'utf8'); // 添加BOM以支持中文
  }

  /**
   * 中间件：验证用户权限
   */
  static requireAdminAuth(req, res, next) {
    // 这里应该实现实际的权限验证逻辑
    // 暂时跳过，实际项目中需要验证用户是否有管理员权限
    if (!req.user) {
      req.user = { id: 1 }; // 临时设置，实际应该从认证中间件获取
    }
    next();
  }

  /**
   * 中间件：请求日志
   */
  static logRequest(req, res, next) {
    console.log(`${req.method} ${req.path}`);
    next();
  }

  /**
   * 中间件：错误处理
   */
  static handleError(err, req, res, next) {
    console.error('Controller Error:', err);
    
    if (err.name === 'MulterError') {
      return res.status(400).json({
        success: false,
        message: '文件上传错误',
        error: err.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? err.message : '请联系管理员'
    });
  }
}

module.exports = CouponImportController;